/**
 * User: yangxiul
 * Date: 16-8-18
 * Time: 上午9:04
 * 土地拓展过程管控统计报表
 */

define("require dojo/_base/declare dojo/_base/lang dojo/_base/array dojo/_base/fx dojo/fx/easing ../../util/ajaxUtil dojo/dom dojo/dom-attr dojo/dom-class dojo/dom-style dojo/on dojo/query dojo/topic ../BaseWidget esri/symbols/SimpleFillSymbol esri/symbols/SimpleLineSymbol esri/graphic esri/layers/GraphicsLayer esri/Color esri/SpatialReference esri/geometry/Point gistech/util/infoUtil dojo/text!./templates/Template.html".split(" "),
    function (require, declare, lang, array, baseFx,easing,ajaxUtil, dom, domAttr, domClass, domStyle, on, query, topic, BaseWidget,SimpleFillSymbol,SimpleLineSymbol,Graphic,GraphicsLayer,Color,SpatialReference,Point,infoUtil,template) {

        return declare([BaseWidget], {
            templateString: template,
            map: null,
            rightTab:null,
            ismove:false,//组件位置移动判断
            grouplist:null,
            projectlist:null,
            departmentType:"company",
            projectType:"mocha",
            projectTypeWords:"核查项目",
            orgFields:null,
            
            reportstarttime:null,
            reportendtime:null,
            
            currentDataList:null,
            
            OrganizationList:null,
            
            companyList:null,
            departmentList:null,
            teamGroupList:null,
            
            datatableheader:null,
            landareaGraphicLayer:null,
            texporttabletitleinfo:"",
            constructor: function (args) {
                this.map = args.map;
                this.rightTab = args.rightTab;
            },

            postCreate: function () {
            	  this.inherited(arguments);
    			this.grouplist = dojo.query(".grouplist li");
    			for(var i=0;i<this.grouplist.length;i++){
    				on(this.grouplist[i], "click",lang.hitch(this,this.changeDepartmentTypeHandler));
    			}
    			
    			this.projectlist = dojo.query(".selProjectTypeList input");
    			for(var i=0;i<this.projectlist.length;i++){
    				on(this.projectlist[i], "click",lang.hitch(this,this.changeProjectTypeHandler));
    			}
    			
    			on(this.tongjiBtn, "click",lang.hitch(this,this.tongjiBtnClick));
    			on(this.exportBtn, "click",lang.hitch(this,this.exportBtnClick));
    			on(this.closebtn,"click",lang.hitch(this,this.closeDialog));
            },

            startup: function () {
                this.inherited(arguments);
                this.init();
            },

            init:function(){
            	this.companyList = [];
            	this.departmentList = [];
            	this.teamGroupList = [];
            	this.tableheader = dojo.query(".t1 .dynamic");
                this.datatableheader = dojo.query(".t2 .dynamic");
                this.orgFields = {
                		"company":"COMPANY#60,GNUM#60,PNUM#100,ZHIBIAO#80,WCD#60",
                		"department":"COMPANY#60,DEPARTMENT#120,GNUM#60,PNUM#100,ZHIBIAO#80,WCD#60",
                		"teamgroup":"COMPANY#60,DEPARTMENT#120,TEAM#100,TEAMLEADER#80,PNUM#100,ZHIBIAO#80,WCD#60"
                };
                this.reportstarttime = dojo.byId("reportstarttime");
                this.reportstarttime.value = reduceformatDate(30,"-");
                
                this.reportendtime = dojo.byId("reportendtime");
                this.reportendtime.value = reduceformatDate(0,"-");
                
            	this.landareaGraphicLayer = new GraphicsLayer(); //创建地块区域面要素展示图层
    			this.map.addLayer(this.landareaGraphicLayer); 
            	this.getOrganizationList();
            	//
            },
            getOrganizationList:function(){
            	ajaxUtil.request("../client/service/landStatisticsController/queryOrganizationList",
            			"departmentType="+this.departmentType+"&projectType=核查项目&startdate="+this.reportstarttime.value+"&enddate="+this.reportendtime.value,lang.hitch(this,function(result){
            				this.OrganizationList = [];
            				var res = result.rows;
            				//this.currentDataList = dojo.clone(result.rows[0].land);
            				for(var i=0;i<res.length;i++){
            					var company = null;
            					for(var j=0;j<this.OrganizationList.length;j++){
            						if(this.OrganizationList[j].name==res[i].COMPANY){
            							company = this.OrganizationList[j];
            							break;
            						}
            					}
            					if(company==null){
            						company = {
            								name:res[i].COMPANY,gnum:1,
            								list:[
            								      {name:res[i].DEPARTMENT,gnum:1,
            								    	  list:[
            								    	        {name:res[i].TEAM,leader:res[i].TEAMLEADER}
            								    	        ]
            								      }
            								      ]
            						};
            						this.OrganizationList.push(company);
            					}else{
            						var departmentlist  = company.list;
            						var department = null;
            						for(var k=0;k<departmentlist.length;k++){
                						if(departmentlist[k].name==res[i].DEPARTMENT){
                							department = departmentlist[k];
                							break;
                						}
                					}
            						if(department == null){
            							department = {name:res[i].DEPARTMENT,gnum:1,
  								    	              list:[
  								    	                     {name:res[i].TEAM,leader:res[i].TEAMLEADER}
  								    	                   ]
  								                     };
            							company.list.push(department);
            							company.gnum++;
            						}else{
            							var team = {name:res[i].TEAM,leader:res[i].TEAMLEADER};
            							department.list.push(team);
            							department.gnum++;
            							company.gnum++;
            						}
            					}
            					res[i]["LANDXHS"] = [];
            					res[i]["PNUM"] = 0;
            					res[i]["ZHIBIAO"] = 2;
            					res[i]["WCD"] =0;
            					this.teamGroupList.push(res[i]);
            				}
            				
            				for(var i=0;i<this.OrganizationList.length;i++){
            					var org = this.OrganizationList[i];
            					//"company"
            					this.companyList.push({COMPANY:org.name,GNUM:org.gnum,PNUM:0,ZHIBIAO:org.gnum*2,WCD:0,LANDXHS:[]});
            					//"department"
            					for(var j=0;j<org.list.length;j++){
            						var depa = org.list[j];
            						this.departmentList.push({COMPANY:org.name,DEPARTMENT:depa.name,GNUM:depa.gnum,PNUM:0,ZHIBIAO:depa.gnum*2,WCD:0,LANDXHS:[]});
            					}
            				}
            				this.loadData();
            			}),function(){
            		console.error("获取组织机构数据失败");
            	});
            },
            tongjiBtnClick:function(){
             	   if( this.reportstarttime.value.replace(" ","")==""|| this.reportendtime.value.replace(" ","")==""){
              		    alert("统计时段不能为空，请选择日期！");
               			return;
             	   }
             	  this.loadData();
            },
            exportBtnClick:function(){
 
            	var param="departmentType="+this.departmentType+"&projectType="+this.projectType+"&startdate="+this.reportstarttime.value+"&enddate="+this.reportendtime.value;
//				infoUtil.showLoading("正在下载...");
				var form = this.landExportForm;
				form.action="../client/service/landStatisticsController/exportlandStatisticsExcel?"+param;
			    form.submit();
			    form.remove();
//			    infoUtil.hideLoading();
 
//                htmlToExcel(this.exporttabletitleinfo,this.exporttableendinfo,"landstatistic", this.currentDataList, 1);//这里的1代表的是border=1的意思。
            },
            changeDepartmentTypeHandler:function(item){
            	 for(var i=0;i<this.grouplist.length;i++){
            		 dojo.toggleClass(this.grouplist[i], "itemselected", false);  
     			}
            	 var selectitem = item.currentTarget;
            	 dojo.toggleClass(selectitem, "itemselected",true);
            	 this.departmentType = selectitem.attributes["value"].value;
            	 this.ResetReportTableHeader();
            },
            changeProjectTypeHandler:function(item){
            	
            	var selectitem = item.currentTarget;
            	this.projectType = selectitem.attributes["value"].value;
            	this.ResetReportTableHeader();
            },
            
            ResetReportTableHeader:function(){
            	var colcount = 0;
    			for(var i=0;i<this.tableheader.length;i++){
    				if(dojo.hasClass(this.tableheader[i], this.departmentType)||dojo.hasClass(this.tableheader[i], this.projectType)){  
    					//domStyle.set(this.tableheader[i],"display","block");
    					//domClass.remove(this.tableheader[i],"colshowstate");
    					dojo.toggleClass(this.tableheader[i],"colshowstate",false);
    					colcount += parseInt(this.tableheader[i].width);
    					
    					//domClass.remove(this.datatableheader[i],"colshowstate");
    					dojo.toggleClass(this.datatableheader[i],"colshowstate",false);
    				}
    				else{
    					//domStyle.set(this.tableheader[i],"display","none");
    					dojo.toggleClass(this.tableheader[i],"colshowstate",true);
    					dojo.toggleClass(this.datatableheader[i],"colshowstate",true);
    				}
    			}
    			 this.rightTab.setWidgetWidth(260+colcount);
    			 this.loadData();
            },
            
            /*
             * 加载数据
             */
            loadData:function(){
            	 var startdate = this.reportstarttime.value;
                 var enddate = this.reportendtime.value;
                 this.projectTypeWords = "";
                 if(this.projectType=="mocha"){
                	 this.projectTypeWords = "核查项目";
                 }
                 if(this.projectType=="qiatan"){
                	 this.projectTypeWords = "洽谈项目";
                 }
                 if(this.projectType=="huoqu"){
                	 this.projectTypeWords = "获取项目";
                 }
                	ajaxUtil.request("../client/service/landStatisticsController/queryLandList",
                			"projectType="+this.projectTypeWords+"&startdate="+startdate+"&enddate="+enddate,lang.hitch(this,function(result){
                	//this.currentDataList = dojo.clone(result.rows);
                	
                	this.createStatisticsReportData(result.rows);
            	}),function(){
                    console.error("统计数据失败");
                });
            },
            createStatisticsReportData:function(source){
            		if(this.departmentType=="company"){
            			this.currentDataList = dojo.clone(this.companyList);
            			fieldnum = 1;
        			}else if(this.departmentType=="department"){
        				this.currentDataList = dojo.clone(this.departmentList);
        			}else if(this.departmentType=="teamgroup"){
        				this.currentDataList = dojo.clone(this.teamGroupList);
        				
        			}
            		
            		for(var i=0;i<source.length;i++){
            			for(var j=0;j<this.currentDataList.length;j++){
            				if(this.departmentType=="company"&&source[i]["COMPANY"]==this.currentDataList[j]["COMPANY"]){

            					this.currentDataList[j].PNUM++;
            					this.currentDataList[j].WCD = Math.round(((this.currentDataList[j].PNUM/this.currentDataList[j].ZHIBIAO)*100)*10)/10;
            					this.currentDataList[j].LANDXHS.push(source[i]["XH"]);
            					break;
            				}
            				if(this.departmentType=="department"
            					&&source[i]["COMPANY"]==this.currentDataList[j]["COMPANY"]
            				    &&source[i]["DEPARTMENT"]==this.currentDataList[j]["DEPARTMENT"]){

            					this.currentDataList[j].PNUM++;
            					this.currentDataList[j].WCD = Math.round(((this.currentDataList[j].PNUM/this.currentDataList[j].ZHIBIAO)*100)*10)/10;
            					this.currentDataList[j].LANDXHS.push(source[i]["XH"]);
            					break;
            				}
            				if(this.departmentType=="teamgroup"
            					&&source[i]["COMPANY"]==this.currentDataList[j]["COMPANY"]
            				    &&source[i]["DEPARTMENT"]==this.currentDataList[j]["DEPARTMENT"]
            				    &&source[i]["TEAM"]==this.currentDataList[j]["TEAM"]){

            					this.currentDataList[j].PNUM++;
            					this.currentDataList[j].WCD = Math.round(((this.currentDataList[j].PNUM/this.currentDataList[j].ZHIBIAO)*100)*10)/10;
            					this.currentDataList[j].LANDXHS.push(source[i]["XH"]);
            					break;
            				}
            			}
            		}
            		this.currentDataList = listSortBy(this.currentDataList,"WCD",'desc');
            	this._inittable(this.currentDataList);
            },
            /*
             * 初始化表格
             */
            _inittable:function(source){
            	var table = dojo.query("#landstatistic").empty();
            	
            	var ths = dojo.query(".t1 th");
            	var headerstr = "<tr>";
            	var colnum = 0;
            	for(var t=0;t<ths.length;t++){
            		var item = ths[t];
            		if(!dojo.hasClass(item, "colshowstate")){  
            			headerstr+= item.outerHTML;
            			colnum++;
            		}
            	}
            	headerstr += "</tr>";
            	
            	this.exporttabletitleinfo = "<tr align='center'><td colspan="+colnum+" style='font-size:18px;font-weight:bold;'>土地拓展过程管控表（数据统计）</td></tr>" +
            			"<tr><td colspan=4>统计时段："+this.reportstarttime.value+"至"+this.reportendtime.value+"</td><td colspan="+(colnum-4)+">统计内容："+this.projectTypeWords+"</td></tr>";
            	this.exporttableendinfo = "<td align='right' colspan="+(colnum-2)+">制表日期："+formatDate(new Date())+"</td><td align='right' colspan=2>制表人："+loginusername.username+"</td>";
            	
            	table.addContent(headerstr);
//            	var datarows = dojo.query("#landstatistic .datarow");
//            	for(var k=0;k<datarows.length;k++){
//            		var item  = datarows[k];
//            		table[0].removeChild(item);
//            	}
            	
                var html="";
                var fields = this.orgFields[this.departmentType].split(",");
            	for (var i=0;i<source.length;i++){
        			var item=source[i];
//        			html+="<tr class='datarow' ><td width=40>"+(i+1)+" </td>";
//        			for(var j=0;j<fields.length;j++){
//        				if(j+3==fields.length){
//        					html+="<td width="+fields[j].split("#")[1]+"><a class='projectnum' value='"+i+"'>"+item[fields[j].split("#")[0]]+"</a></td>";
//        				}else if(j==fields.length-1){
//        					html+="<td width="+fields[j].split("#")[1]+">"+item[fields[j].split("#")[0]]+"%</td>";
//        				}else{
//        					html+="<td width="+fields[j].split("#")[1]+">"+item[fields[j].split("#")[0]]+"</td>";
//        				}
//        			}
        			
        			html+="<tr class='datarow' ><td >"+(i+1)+" </td>";
        			for(var j=0;j<fields.length;j++){
        				if(j+3==fields.length){
        					var pum = item[fields[j].split("#")[0]];
        					html+="<td ><a class='projectnum' value='"+i+"'>"+(pum>0?pum:"")+"</a></td>";
        				}else if(j==fields.length-1){
        					var wcd = item[fields[j].split("#")[0]];
        					var style = wcd<100?"style='color:#f00;'":"";
        					html+="<td "+style+" >"+wcd+"%</td>";
        				}else{
        					html+="<td >"+item[fields[j].split("#")[0]]+"</td>";
        				}
        			}
        		}
            	html=html.replace(/undefined/g,'');
            	table.addContent(html);
            	//字母列表项点击事件
    			dojo.query(".t2 a").map(dojo.hitch(this,function(item,index){  
    				dojo.connect(item,"onclick",dojo.hitch(this,function(){  
    	            	var dataidx = item.attributes["value"].value;
    	            	var dataObj  = this.currentDataList[dataidx];
    	            	var wheresql = dataObj.LANDXHS[0];
    	            	for(var i=1;i<dataObj.LANDXHS.length;i++){
    	            		wheresql += "','"+dataObj.LANDXHS[i];
    	            	}
    	            	var params = {
    	    					url:ioc.sddc.landFeatureLayer,//"http://poc-pc:6080/arcgis/rest/services/SDDC/MyMapService/MapServer/0",
    	    					wheresql:"XH in ('"+wheresql+"')"
    	    			};
    	            	this.queryListBySQL(params);
    	            	this.landareaGraphicLayer.clear();
    				}));  
    			}));
 
            },
            /*数据查询与地图展布*/
            queryListBySQL:function(params){
            	var QueryTask = new esri.tasks.QueryTask(params.url);//"http://192.168.120.69:6080/arcgis/rest/services/POC/kehu/MapServer/0");
            	var query = new esri.tasks.Query();

            	query.where = params.wheresql;//"Code = '"+attr["Code"]+"'"; 
            	query.outFields = ["*"]; 
            	query.outSpatialReference = new esri.SpatialReference(4326);//查询结果的输出投影为经纬度

            	query.returnGeometry = true; 
            	QueryTask.execute(query, dojo.hitch(this,this.queryResultHandler),function(error){
            		alert(error);
            	}); 
            },
            queryResultHandler:function(queryResult){
    			if (queryResult.features.length == 0) { 
        			return; 
        		} 
        		if (queryResult.features.length > 0) { 
        			var landlist = queryResult.features;
        			this.addLandsFeatureLayer(landlist);
        		}
    		} ,
    		 addLandsFeatureLayer:function(landlist){
    			var linesymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
    					new Color([0,0,0,0.5]), 0.5);
    			var symbols = [
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([150, 150, 150, 0.35])),
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([56, 168, 0, 0.35])),
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([139, 209, 0, 0.35])),
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([255, 255, 0, 0.35])),
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([255, 128, 0, 0.35])),
    			               new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,linesymbol,new Color([255, 0, 0, 0.35]))];

    			
    			for (var i = 0; i < landlist.length; i++) { 
    				var land = landlist[i]; 
    				var myPolygon = {"geometry":land.geometry,
    						"attributes":land.attributes,
    						"infoTemplate":mapinfoTemplate["LandFeatureLayer"].template
    							};
    				var pgra = new esri.Graphic(myPolygon);
    				var idx = 5-i%6;
    				pgra.setSymbol(symbols[idx]);
    				this.landareaGraphicLayer.add(pgra);
    			}
    			this.map.centerAndZoom(landlist[0].geometry.getCentroid(),15);			
    			on(this.landareaGraphicLayer,"click", lang.hitch(this,function(evt) {

    			}));
    		},
    		 closeDialog:function(){
     			this.inherited("closeDialog",arguments);
     			this.rightTab.expandBtn.click();
     			this.landareaGraphicLayer.clear();
     			this.destroy();
     		},
            destroy: function () {
                var widgets = this.widgets;
                for (var name in widgets) {
                    if (widgets[name]) {
                        widgets[name].destroy();
                    }
                }
                this.inherited(arguments);
            },
      
        });
    });